using System;
using System.Windows;
using System.Threading;

namespace ibba.src.norisk
{
    public partial class App : Application
    {
        public static string XMLServidores { get; private set; }

        public App()
        {
            InitializeComponent();

            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;
        }

        public static MainPage MainPage
        {
            get { return App.Current.RootVisual as MainPage; }
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("pt-BR");
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("pt-BR");

            XMLServidores = e.InitParams["XML_Servidores"];

            AppHelper.Servidor = this.Host.Source.DnsSafeHost;

            if (string.IsNullOrEmpty(AppHelper.Servidor))
                AppHelper.Servidor = "itaubba";
            else
                AppHelper.Servidor.Trim();

            AppHelper.IdSistema = int.Parse(e.InitParams["IdSistema"]);
            AppHelper.NomeSistema = "NORISK";

            AppHelper.LoginUsuario = System.IO.Path.GetFileName(e.InitParams["User.Identity.Name"]);
            AppHelper.NomeUsuario = System.IO.Path.GetFileName(e.InitParams["FullName"]);

            ObterPerfil();
        }

        private void ObterPerfil()
        {
            ServiceFactory.GetInstance().ServiceAcesso.BeginObterPerfil(AppHelper.LoginUsuario, AppHelper.IdSistema,
                                                                        CallBackObterPerfil, ServiceFactory.GetInstance().ServiceAcesso);
        }

        private void CallBackObterPerfil(IAsyncResult pAsyncResult)
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            {

                AppHelper.Perfil = ((ServiceAcesso.IAcesso)pAsyncResult.AsyncState).EndObterPerfil(pAsyncResult);

                this.RootVisual = new MainPage();
            });

        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            MessageBoxHelper.ShowErro("Erro", e.ExceptionObject.Message, e.ExceptionObject.StackTrace);
        }


    }
}
